package com.chief;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(-1)
public class DataSourceExchange {


    @Before("@annotation(TargetDataSource)")
    public void before(JoinPoint joinPoint) {
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        boolean isMethodAop = method.isAnnotationPresent(TargetDataSource.class);
        if (isMethodAop) {
            TargetDataSource datasource = method.getAnnotation(TargetDataSource.class);
            DataSourceHolder.setDataSources(datasource.value());
        } else {
            if (joinPoint.getTarget().getClass().isAnnotationPresent(TargetDataSource.class)) {
                TargetDataSource datasource = joinPoint.getTarget().getClass().getAnnotation(TargetDataSource.class);
                DataSourceHolder.setDataSources(datasource.value());
            }
        }
    }

    @After("@annotation(TargetDataSource)")
    public void after() {
        DataSourceHolder.clearDataSource();
    }
}
